from flask_restful import Resource, Api
from flask import Blueprint, request, session
from libs.response import generate_response
from werkzeug.security import check_password_hash
from model.models import User, db

loginapi_bp = Blueprint("loginapi", __name__)
api = Api(loginapi_bp)


class LoginApi(Resource):

    def post(self):
        user_info = request.get_json()

        account = user_info.get("account")  # 获取账号
        password = user_info.get("password")  # 获取密码
        if not all([account, password]):  # 判断参数是否完整
            return generate_response(message="参数不完整", status_code=4000)

        user = User.query.filter(User.account == account).first()

        # 查找数据库用户是否存在 # 验证密码
        if user is None or not check_password_hash(user.password, password):
            return generate_response(message="用户名或密码错误", status_code=4000)
        my_user = User(account=account, password=password)
        try:
            db.session.add(my_user)
            db.session.commit()
            session["account"] = account
            session["password"] = password
        except Exception as e:
            print(e, "失败")
            db.session.rollback()
        return generate_response(message="登陆成功", status_code=2000)


api.add_resource(LoginApi, "/loginapi")
api.add_resource(LoginApi, "/loginapi/<id>", endpoint='stuapiid')
